﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using NetMicro.EventBus.Extensions;
using NetMicro.EventBus.Messages;

namespace NetMicro.EventBus.Policies
{
    public class EventErrorHandler : IEventErrorHandler
    {

        public EventErrorHandler(IEventRetryPolicy eventRetryPolicy, IEventErrorSendDeadLetter eventErrorSendDead, IOptions<EventBusOptions> options)
        {

            EventRetryPolicy = eventRetryPolicy;
            EventErrorSendDeadLetter = eventErrorSendDead;
            Options = options;
        }
        private IEventRetryPolicy EventRetryPolicy { get; }



        private IEventErrorSendDeadLetter EventErrorSendDeadLetter { get; }

        private IOptions<EventBusOptions> Options { get; }

        public async Task OnErrorAsync(MessageTransfer messageTransfer, CancellationToken cancellationToken)
        {
            if (!messageTransfer.HaveRetry(0))
            {
                if (!Options.Value.UseDeadLetter)
                    return;
                await EventErrorSendDeadLetter.OnSendDeadLetterAsync(messageTransfer, cancellationToken: cancellationToken);
                return;
            }
            await EventRetryPolicy.OnRetryAsync(messageTransfer, cancellationToken);
        }
    }
}
